package com.frxuexi.mymvi

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class NewsViewModel @Inject constructor(private val newsRepository:NewsRepository):ViewModel() {

    //获取一个存放管理意图的通道
    val channel = Channel<NewsIntent>(Channel.UNLIMITED)

    //获取一个可变状态，用于更新UI
    private var _state= MutableStateFlow<NewsState>(NewsState.onLoading)
    val state:StateFlow<NewsState>
        get() = _state

    init {
        viewModelScope.launch {
            //接收到意图
            channel.receiveAsFlow().collect{
                when(it){
                    is NewsIntent.getNews->{
                        getNews(it.page)
                    }

                    else -> {}
                }
            }
        }
    }

    private fun getNews(page: Int) {
        viewModelScope.launch {
            newsRepository.getNews(page)
                .flowOn(Dispatchers.IO)
                .catch {
                    it.printStackTrace()
                }
                .collect{
                    if(it.code==0){
                        _state.value=NewsState.onSuccess(it.data.records)
                    }else{
                        _state.value=NewsState.onError(it.msg)
                    }
                }
        }
    }


}